package org.parosproxy.paros.core.proxy.custom;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class URLMonitor {

	Set<String> setMonitorUrl = new HashSet<String>();
	Map<String, Integer> mapMonitorPort = new HashMap<String, Integer>();
	private static final Pattern removeParameters = Pattern.compile("\\?[^/]+$", Pattern.CASE_INSENSITIVE | Pattern.COMMENTS | Pattern.MULTILINE | Pattern.DOTALL | Pattern.UNICODE_CASE
			| Pattern.UNIX_LINES);

	private static URLMonitor INSTANCE;

	private static Log log = LogFactory.getLog(URLMonitor.class);

	private URLMonitor() {
		// TODO Auto-generated constructor stub
	}

	public static URLMonitor getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new URLMonitor();
		}
		return INSTANCE;
	}

	public void addSecureLink(String client, String url) {
		int index = url.indexOf("?");
		if (index != -1) {
			url = url.substring(0, index);
		}

		int methodIndex = url.indexOf("//") + 2;
		String method = url.substring(0, methodIndex);
		int pathIndex = url.indexOf("/", methodIndex);
		String host = url.substring(methodIndex, pathIndex);
		String path = url.substring(pathIndex);
		int port = 443;
		int portIndex = host.indexOf(":");

		if (portIndex != -1) {
			host = host.substring(0, portIndex);
			try {
				port = Integer.parseInt(host.substring(portIndex + 1));
			} catch (NumberFormatException ex) {
				port = 443;
			}

		}
		path = path.replace("\\?[^/]+$", "");
		url = method + host + path;

		log.debug("Insertando en el set: " + client + url);
		synchronized (setMonitorUrl) {
			setMonitorUrl.add(client + url);
		}
		log.debug("Insertando en el map: " + client + url + " ; " + port);
		synchronized (mapMonitorPort) {
			mapMonitorPort.put(client + url, port);
		}

	}

	public int getSecurePort(String client, String url) {
		if (mapMonitorPort.containsKey(client + url)) {
			return mapMonitorPort.get(client + url);
		} else {
			return 443;
		}
	}

	public boolean isSecureLink(String client, String url) {
		int index = url.indexOf("?");
		if (index != -1) {
			url = url.substring(0, index);
		}
		boolean isSecure = setMonitorUrl.contains(client + url);
		return isSecure;
	}

}
